from flask import Blueprint, request, jsonify
from sqlalchemy.exc import SQLAlchemyError

from extensions import db
from models import User
from utils.response import error_response, success_response
from flask_jwt_extended import jwt_required, get_jwt_identity

api = Blueprint('users', __name__)

@api.route('/', methods=['GET'])
def list_users():
    page = request.args.get('page', 1, type=int)
    limit = request.args.get('limit', 10, type=int)
    role = request.args.get('role')
    is_deleted = request.args.get('is_deleted')

    query = User.query
    if role:
        query = query.filter_by(role=role)
    if is_deleted is not None:
        query = query.filter_by(is_deleted=bool(int(is_deleted)))

    total = query.count()
    users = query.offset((page - 1) * limit).limit(limit).all()

    return jsonify(success_response(
        data=[u.to_dict() for u in users],
        msg='获取用户列表成功',
        code=0
    ) | {'count': total})

@api.route('/', methods=['POST'])
@jwt_required()
def create_user():
    data = request.get_json() or request.form
    username = data.get('username', '').strip()
    password = data.get('password', '').strip()
    email = data.get('email', '').strip()
    role = data.get('role', 'user')

    if not all([username, password, email]):
        return jsonify(error_response('用户名、密码和邮箱不能为空'))

    if User.query.filter_by(username=username).first():
        return jsonify(error_response('该用户名已存在'))

    try:
        user = User(username=username, email=email, role=role)
        user.set_password(password)
        db.session.add(user)
        db.session.commit()
        return jsonify(success_response({'user': user.to_dict()}, msg='添加成功'))
    except SQLAlchemyError as e:
        db.session.rollback()
        return jsonify(error_response(f'数据库错误: {str(e)}'))

@api.route('/<int:user_id>', methods=['DELETE'])
@jwt_required()
def delete_user(user_id):
    user = User.query.get_or_404(user_id)
    user.is_deleted = True  # 逻辑删除

    db.session.commit()
    return jsonify(success_response(msg=f'用户 {user.username} 已标记为删除'))

@api.route('/<int:user_id>', methods=['GET'])

def get_user(user_id):
    user = User.query.get_or_404(user_id)
    return jsonify(success_response(user.to_dict()))

@api.route('/<int:user_id>', methods=['PUT'])

def update_user(user_id):
    data = request.get_json() or request.form
    user = User.query.get_or_404(user_id)

    user.username = data.get('username', user.username)
    user.email = data.get('email', user.email)
    user.role = data.get('role', user.role)
    if 'is_deleted' in data:
        user.is_deleted = bool(int(data.get('is_deleted')))

    db.session.commit()
    return jsonify(success_response({'user': user.to_dict()}, msg='用户信息已更新'))